﻿$.dataOptions = {
	dateFormat: 'dd-MMM-yyyy',
	dateTimeFormat: 'dd-MMM-yyyy hh:mm:ss',
	dataDelimiter: '-',
	datePickerDateFormat: 'dd-MM-yy'
};

var page = (function (page) {
	page.showLoader = function () {
		$('#page-loader').show();
	}
	page.hideLoader = function () {
		$('#page-loader').hide();
	}
	return page;
} (page || {}));
	

Date.prototype.format = function (f) {
	var PadZero = function (n) { return (n < 10) ? ('0' + n) : n; }
	var MonthNames=['January','February','March','April','May','June','July','August','September','October','November','December'];
	var ShortMonthNames=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
	
	var d = this.getDate();
	var M = this.getMonth();
	var y = this.getFullYear();
	var h = this.getHours();
	var m = this.getMinutes();
	var s = this.getSeconds();

	f = f.replace('dd', '#a#');
	f = f.replace('d', '#b#');
	f = f.replace('MMMM', '#c#');
	f = f.replace('MMM', '#d#');
	f = f.replace('MM', '#e#');
	f = f.replace('M', '#f#');
	f = f.replace('yyyy', '#g#');
	f = f.replace('yy', '#h#');

	f = f.replace('hh', '#i#');
	f = f.replace('h', '#j#');
	f = f.replace('mm', '#k#');
	f = f.replace('m', '#l#');
	f = f.replace('ss', '#m#');
	f = f.replace('s', '#n#');

	f = f.replace('#a#', PadZero(d));
	f = f.replace('#b#', d);
	f = f.replace('#c#', MonthNames[M]);
	f = f.replace('#d#', ShortMonthNames[M]);
	f = f.replace('#e#', PadZero(M));
	f = f.replace('#f#', M);
	f = f.replace('#g#', y);
	f = f.replace('#h#', PadZero(y % 100));

	f = f.replace('#i#', PadZero(h));
	f = f.replace('#j#', h);
	f = f.replace('#k#', PadZero(m));
	f = f.replace('#l#', m);
	f = f.replace('#m#', PadZero(s));
	f = f.replace('#n#', s);

	return f; 
};


(function ($) {
	$.fn.setFormattedContent = function (content, obj) {		
		if(content!=null && !$.isArray(content) && !$.isPlainObject(content))
			content=content+'';	
		return this.each(function(){
			var setMethod = 'html';
			if ($(this).prop('tagName') == 'INPUT' || $(this).prop('tagName') == 'SELECT')
			{
				if($(this).attr('type')=='checkbox')
				{
					$(this).prop('checked', content && content != 'false')
					return;
				}
				setMethod = 'val';
			}
			var fmt = $(this).attr('format');
			var type = $(this).attr('type');
			if (fmt) {
				if (window[fmt] != null) {
					var fn = eval(fmt);
					if (fn) {
						$(this).get(0).formatFunction = fn;
						$(this)[setMethod]($(this).get(0).formatFunction(content, obj));
					}
				}
			}
			else {
				if(content)
				{
					if (!$.isArray(content) && content.substring(0, 6) == '/Date(') {
						content = content.replace(/\/Date\(/g, '').replace(/\)\//g, '');
						fmt = $.dataOptions.dateFormat;
						if(type == 'datetime')
							fmt = $.dataOptions.dateTimeFormat
						if($(this).hasClass('date-picker'))
						{
							fmt = $.dataOptions.datePickerDateFormat
							$(this)[setMethod]($.datepicker.formatDate(fmt, new Date(parseInt(content))));					
						}
						else
							$(this)[setMethod]((new Date(parseInt(content))).format(fmt));
					}
					else 
					{
						var adjusted = content;
						if($(this).is('textarea') && $(this).attr('data-type') == 'array')
							adjusted = content.join('\n');													
						$(this)[setMethod](adjusted);
					}
				}
			}
		});
	}
	$.fn.validate = function () {
			
			var patterns={
				"int" : '/^-?\\d*$/',
				"decimal" : '/^-?\\d*\\.?\\d{0,#decimalplaces#}$/',
				"email" : '/^([a-zA-Z0-9\\\'_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/',
				//"password" : '/^.*(?=.{8,})((?=.*\\d)|(?=.*\\W+))(?=.*[A-Z]).*$/',
				"ipaddress" : '/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/'
			};

			var allValid = true;
			this.each(function(){
				var valid = true;
				var ans = $(this).val();
				var message = $(this).attr('title');
				var required = $(this).attr('required');
				var pattern = $(this).attr('pattern');
				var func = $(this).attr('function');
				var type = $(this).attr('type');
				var matchid = $(this).attr('matchid');

				var decimalplaces = $(this).attr('decimalplaces');
				var maxlength = $(this).attr('maxlength');
				var min = $(this).attr('min');
				var max = $(this).attr('max');

				if(!decimalplaces)
					decimalplaces=2;

				var messageId=$(this).attr('id')+'-validator';
				$('#'+messageId).hide();

				$(this).removeClass('invalid');

				if (required) {
					if (ans == null || ans == '' || ans == 'Select...' || ans == '- Select -') {
						valid = false;
						message = 'This is a required field.';
					}
				}
				if (ans && ans != '')
				{
					if (valid && pattern) {
						valid = (ans.match(new RegExp(pattern)) != null);
						//message='Please match the format: '+message;
					}
					if (valid && matchid) {
						if (ans && ans != '') {
							valid = ans = $(matchid).val();
						}
					}
					if (valid && func) {
						var vf = eval(func);
						valid = vf(ans);
					}
					if (valid && type){
						if(patterns[type])
						{							
							var p = patterns[type];
							p=p.replace(/#decimalplaces#/g, decimalplaces);
							valid = (ans.match(eval(p)) != null);
							switch(type)
							{
								case 'email':
									message= 'Please enter a valid email address';
									break;
								case 'url':	
									message= 'Please enter a valid web address';
									break;
								case 'int':
									message= 'Please enter a valid number';
									if(valid)
									{										
										valid = (!min || parseInt(ans)>=parseInt(min)) && (!max || parseInt(ans)<=parseInt(max))										
										if(min && max)
											message='Number must be between '+min+' and '+max;
										else
										{
											if(min)
												message='Number must be greater or equal to ' + min;
											if(max)
												message='Number must be less than or equal to ' + max;
										}
									}
									break;
								case 'decimal':
									message= 'Please enter a valid number (up to '+decimalplaces+' decimal places)';
									if(valid)
									{										
										valid = (!min || parseFloat(ans)>=parseFloat(min)) && (!max || parseFloat(ans)<=parseFloat(max))										
										if(min && max)
											message='Number must be between '+min+' and '+max;
										else
										{
											if(min)
												message='Number must be greater or equal to ' + min;
											if(max)
												message='Number must be less than or equal to ' + max;
										}
									}
									break;
								case 'ipaddress':
									message= 'Please enter a valid ipaddress';
									break;
								/*
								case 'password':
									message= 'Please enter a valid password. Passwords must be at least 8 characters, contain uppercase, lowercase and at least one number or special character';
									break;
								*/
								case 'number':
									break;
							}
						}
					}					
				}
				if (!valid)
				{					
					var messageSpan=$('#'+messageId);
					if(messageSpan.length==0){
						messageSpan = $('<span>').attr({id: messageId}).addClass('validator-message');
						$(this).after(messageSpan);
					}
					messageSpan.html(message)
					messageSpan.show();
					$(this).addClass('invalid');
				}
				allValid &= valid;

			});
		return allValid;
	}
})(jQuery);

$.setData = function (name, values) {
	$('input, span, textarea, select').each(function () {
		var e = this;
		var id = e.id;

		var parts = id.split($.dataOptions.dataDelimiter);
		if (parts.length < 2 || parts[0] != name)
			return;
		var ctx = values;
		for (var j = 1; j < parts.length; j++) {
			if (ctx)
				ctx = ctx[parts[j]];
		}
		if (ctx == null)
			return;
		$(e).setFormattedContent(ctx, values);
	});
}

$.getData = function (name, validate) {
	var data = {};
	var valid = true;
	$('input, textarea, select').each(function () {
		var e = this;
		var id = e.id;

		var parts = id.split($.dataOptions.dataDelimiter);
		if (parts.length < 2 || parts[0] != name)
			return;

		var ctx = data;
		for (var j = 1; j < parts.length - 1; j++) {
			if (ctx[parts[j]] == null)
				ctx[parts[j]] = {};
			ctx = ctx[parts[j]];
		}
		if ($(this).attr('type') == 'checkbox')
			ctx[parts[parts.length - 1]] = $(e).is(':checked'); // $(e).val() == 'on' ;
		else {
			if (validate)
				valid &= $(e).validate();
			var val = $(e).val();
			if ($(this).attr('data-type') == 'array')
			{
				if($(this).is('textarea'))
					val = val.split('\n');
			}
			ctx[parts[parts.length - 1]] = val;
		}
	});
	if (validate)
		return { data: data, valid: valid };
	else
		return data;
}

$.validate = function(name) {
	return $.getData(name, true).valid;	
}

$(function () {
	$('.date-picker').attr('readonly', true)
			.datepicker({
				changeYear: true,
				dateFormat: $.dataOptions.datePickerDateFormat
			});
	if (!('autofocus' in document.createElement("input"))) {
		$('input[autofocus]').focus();
    }
});

$.save = function (r) {
	if (!r.errorselector)
		r.errorselector = '#page-errors';
	$.hideErrors(r.errorselector);
	if (!r.bypassValidation && !$.validate(r.name))
		return;
	page.showLoader();
	var d = $.getData(r.name);
	var data = $.extend(true, {}, r.model, d);
	var json = JSON.stringify(data);
	$.ajax({
		url: r.url,
		type: 'POST',
		data: json,
		dataType: 'json',
		contentType: 'application/json',
		success: function (data, status, xhr) {
			if(r.autoHideLoader != false)
				page.hideLoader();
			if (!data.Success) {
				page.hideLoader();
				$.showErrors(data.Message, r.errorselector);
				return;
			}
			if (r.onsuccess)
				return r.onsuccess(data);
			if (!r.successurl)
				r.successurl = '../';
			top.location.href = r.successurl;
		},
		error: function (xhr, status, error) {
			page.hideLoader();
			if (r.onerror)
				return r.onerror(error);
		}
	});
}

$.hideErrors = function(selector){
	$(selector).html('').hide();
}

$.showErrors = function(el, selector){
	if(!$.isArray(el))
		el = [el];
	var html='<ul>';
	for (var i=0;i<el.length;i++)
	{
		html+='<li>'+el[i]+'</li>'
	}
	html+='</ul>'
	$(selector).html(html).show();
}